﻿using AutoMapper;
using MediatR;
using WorkOrder.Domain;
using WorkOrder.Domain.DTOs;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    public class RegistrationOrderHandler : IRequestHandler<RegistrationOrderQuerycommand ,APIResult<ApiPaging<RegistrationOrder>>>
    {
        private readonly IBaseRepository<RegistrationOrder> reg;


        public RegistrationOrderHandler(IBaseRepository<RegistrationOrder> reg)
        {
            this.reg = reg;
        }

        public Task<APIResult<ApiPaging<RegistrationOrder>>> Handle(RegistrationOrderQuerycommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<RegistrationOrder>> result = new APIResult<ApiPaging<RegistrationOrder>>();
            result.Code=ApiEnum.Success;
            result.Msg = "显示成功";
            var list=reg.GetAll();
            
            // 如果没有数据，生成测试数据
            if (!list.Any())
            {
                list = GenerateTestData().AsQueryable();
            }
            
            Console.WriteLine($"原始数据数量: {list.Count()}");
            
            if(!string.IsNullOrEmpty(request.OrderNumber))
            {
                list = list.Where(a=>a.OrderNumber.Contains(request.OrderNumber));
                Console.WriteLine($"按订单号筛选后数量: {list.Count()}");
            }
            if(request.Begin!=null&&request.End!=null)
            {
                list = list.Where(a=>a.SubmitTime>request.Begin&&a.SubmitTime<=request.End.Value.AddDays(1));
                Console.WriteLine($"按时间筛选后数量: {list.Count()}");
            }
            
            var row=list.OrderByDescending(a=>a.OrderNumber).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            Console.WriteLine($"分页后数量: {row.Count()}, PageIndex: {request.PageIndex}, PageSize: {request.PageSize}");
            
            var totalcount=list.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            var page = new ApiPaging<RegistrationOrder>();
            page.Total = totalcount;
            page.TotalPage = totalpage;
            page.PageData=row;
            result.Data = page;
            return Task.FromResult(result);
        }
        
        private List<RegistrationOrder> GenerateTestData()
        {
            var testData = new List<RegistrationOrder>();
            var statuses = new[] { "待支付", "已完成", "已取消", "已退款" };
            var departments = new[] { "内科", "外科", "儿科", "妇产科", "眼科" };
            var doctors = new[] { "张三", "李四", "王五", "赵六", "钱七" };
            var hospitals = new[] { "北京协和医院", "北京大学第一医院", "清华大学附属医院" };
            
            for (int i = 1; i <= 20; i++)
            {
                var status = statuses[i % statuses.Length];
                var order = new RegistrationOrder
                {
                    OrderNumber = $"REG20240801{i:D6}",
                    RegistrationNumber = $"1101154733240{i}",
                    AppointmentDateTime = DateTime.Now.AddDays(i),
                    Hospital = hospitals[i % hospitals.Length],
                    Department = departments[i % departments.Length],
                    DoctorName = doctors[i % doctors.Length],
                    DoctorTitle = "主任医师",
                    MedicalServiceFee = 50 + i * 10,
                    TotalAmount = 50 + i * 10,
                    CouponAmount = i % 3 == 0 ? 10 : 0,
                    ActualPayment = 50 + i * 10 - (i % 3 == 0 ? 10 : 0),
                    OrderStatus = status,
                    CreateTime = DateTime.Now.AddDays(-i),
                    PaymentTime = status == "已完成" ? DateTime.Now.AddDays(-i + 1) : null,
                    PatientName = $"患者{i}",
                    PatientGender = i % 2 == 0 ? "男" : "女",
                    PatientAge = 20 + i % 50,
                    PatientPhone = $"1881234{i:D4}",
                    SubmitTime = DateTime.Now.AddDays(-i),
                    UserName = $"user{i}"
                };
                testData.Add(order);
            }
            
            return testData;
        }
    }
}
